<template>
  <div class="clearfix">
    <a-upload :action="storage.uploadURL"
              :data="handleUploadData"
              :headers="headers"
              @preview="handlePreview"
              @change="handleChange"
              :beforeUpload="imageBeforeUpload"
              :remove="handleFileRemove"
              :fileList="fileList"
              :disabled="isQuery || disabled"
              :showUploadList="showUploadList"
              :markText="markText"
              :listType="listType"
              :accept="accept">
      <div v-if="fileList.length < limit && !isQuery"
           :disabled="disabled">
        <a-icon type="plus" />
        <div class="ant-upload-text"> 图片上传 </div>
      </div>
    </a-upload>
    <VImgPreview ref="imgDeal"
                 :url="previewImage" />
  </div>
</template>
<script>
import { storage } from '@zh/common-utils/http'
import { getFileList, saveFile, deleteFile } from './../api/upload'
import { Modal } from 'ant-design-vue'
import VImgPreview from '../VImgPreview/VImgPreview.vue'
import { getFileInfoList } from './../api/file.js'
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
export default {
  name: 'ZImageUploader',
  title: '图片上传',
  components: { VImgPreview },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: Array,
      default: function () {
        return []
      },
      description: '附件列表默认值'
    },
    isQuery: {
      type: Boolean,
      default: false,
      description: '当值为true时表示只读'
    },
    disabled: {
      type: Boolean,
      default: false,
      description: '是否禁用'
    },
    limitSize: {
      type: Number,
      required: false,
      default: null,
      description: '附件组'
    },
    accept: {
      type: String,
      required: false,
      default: 'image/*',
      description: '允许传值类型'
    },
    configGroup: {
      type: String,
      required: false,
      default: null,
      description: '附件组'
    },
    showUploadList: {
      type: Boolean,
      default: true,
      description: '当值为true时表示显示当前的附件列表'
    },
    listType: {
      type: String,
      default: 'picture-card',
      description:
        '上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card'
    },
    parentId: {
      type: String,
      default: '',
      description: '附件ID,必填'
    },
    limit: {
      type: Number,
      default: 2,
      description: '上传限制数量'
    },
    fileSize: {
      type: Number,
      default: 200,
      description: '附件大小'
    },
    bucketName: {
      type: String,
      default: 'zongheng',
      description: '当前归属系统所在的空间名称'
    },
    systemName: {
      type: String,
      default: 'zongheng',
      description: '归属系统名称'
    },
    markText: {
      type: String,
      default: 'markText',
      description: '备注当前附件说明'
    },
    headers: {
      type: Object,
      default: null
    },
    beforeUpload: {
      type: Function,
      default: null,
      description: '上传前'
    }
  },
  data () {
    return {
      storage,
      previewImage: '',
      fileList: [],
      flag: true,
      fileData: {}
    }
  },
  watch: {
    parentId () {
      this.getImageList()
    },
    value: {
      handler (value) {
        if (this.parentId) {
          return
        }
        if (value.length > 0 && value[0] && !value[0].uid) {
          this.getFileInfoListFun(value)
          return
        }
        if (value) {
          this.fileList = value
        }
      },
      immediate: true,
      deep: true
    }
  },
  created () {
    if (this.parentId != '') {
      this.getImageList()
    }
  },
  methods: {
    getFileInfoListFun (value) {
      getFileInfoList(value).then(response => {
        this.fileList = response.map(item => {
          item.url = storage.downloadURL + item.uid
          item.status = 'done'
          return item
        })
      })
    },
    validator (fn) {
      const _this = this
      let msg = ''
      if (_this.fileList.length == 0 && _this.fileList.length == 0) {
        msg = '图片不能为空'
      }
      if (this.fileList.length > this.limit) {
        msg = '图片数量不能大于限定值'
      }
      fn(msg)
    },
    validImgFormer (fileName) {
      let reg = /\.(png|jpg|jpeg|gif)$/
      return reg.test(fileName)
    },
    imageBeforeUpload (image) {
      const isLt10M = image.size / 1024 / 1024 < this.fileSize
      const typeOk = image.type.indexOf('image') > -1
      return new Promise(async (resolve, reject) => {
        if (!isLt10M) {
          this.$notify.error('图片大小不能大于' + this.fileSize + 'MB')
          reject(image)
        } else if (!typeOk) {
          this.$notify.error('上传图片格式错误！')
          reject(image)
        } else {
          if (this.beforeUpload instanceof Function) {
            this.beforeUpload(image, resolve, reject)
          } else {
            resolve()
          }
        }
      })
    },
    handleUploadData (file) {
      if (this.bucketName == '' || this.systemName == '') {
        return
      }
      const data = {
        uid: file.uid,
        md5: '',
        fileName: file.name,
        chunked: false,
        bucketName: this.bucketName,
        systemName: this.systemName,
        markText: 'markText'
      }
      this.fileData = data
      return data
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.$refs.imgDeal.open()
    },
    handleChange (info) {
      // this.fileList = fileList;
      let fileList = [...info.fileList]

      if (fileList.length > this.limit) {
        this.$notify.error('超出上传文件最大数量限制')
        return false
      }

      fileList = fileList.map((file) => {
        const newfile = {
          uid: file.uid,
          name: file.name,
          status: file.status,
          parentId: this.parentId,
          url: '',
          configGroup: this.configGroup
        }

        if (file.response) {
          // Component will show file.url as link
          if (file.response.code == 0) {
            newfile.url = storage.downloadURL + file.response.data.key
            newfile.uid = file.response.data.key
            newfile.status = 'done'
          } else {
            newfile.status = 'error'
          }
        } else {
          newfile.url = file.url
        }
        return newfile
      })

      this.fileList = fileList
      if (info.file.status === 'done') {
        if (this.parentId != '') {
          this.fileSubmit(this.parentId, fileList, this.configGroup).then(
            (res) => {
              this.$emit('change', fileList, 'over')
            }
          )
        }
      }
      this.$emit('change', fileList, info.file.status)
    },
    handleFileRemove (info) {
      return new Promise((resolve, reject) => {
        const _info = info
        // //删除附件关系】
        Modal.confirm({
          title: '提示',
          content: '删除将会立即生效,确认删除吗？',
          destroyOnClose: true,
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            if (
              _info.parentId != '' &&
              _info.uid != '' &&
              _info.configGroup != ''
            ) {
              const options = {
                businessId: _info.parentId,
                fileId: _info.uid,
                fileType: _info.configGroup
              }
              deleteFile(options).then((response) => {
                this.getImageList()
              })
            } else {
              resolve(true)
            }
          },
          onCancel () {
            resolve(false)
          }
        })
      })
    },
    fileSubmit (parentId, fileList, configGroup) {
      const ff = []
      fileList.map(function (val) {
        const up = {
          uid: val.uid,
          fileName: val.name,
          parentId: parentId,
          businessType: 'mb',
          configGroup: configGroup
        }
        ff.push(up)
      })
      const options = {
        parentId: parentId,
        configGroup: configGroup,
        list: ff
      }
      return saveFile(options)
    },
    getImageList () {
      const options = {
        businessId: this.parentId,
        fileType: this.configGroup
      }
      getFileList(options).then((response) => {
        let arrlist = response
        arrlist = arrlist.map((arrData) => {
          const newfile = {
            uid: arrData.fileId,
            fileName: arrData.fileName,
            status: 'done',
            parentId: arrData.businessId,
            configGroup: arrData.fileType,
            url: storage.downloadURL + arrData.fileId
          }
          this.fileList.push(newfile)
          return newfile
        })

        this.fileList = arrlist
        this.$emit('input', arrlist)
      })
    },
    imageValidator () {
      return this.fileList.length > 0
    }
  }
}
</script>
<style lang="less" scoped>
.ant-upload-select-picture-card i {
  font-size: calc(var(--font-size-20) + 12px);
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
